package com.miya.demo.support.rabbitmq.topic;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 主题演示消费者
 *
 * @author Caixiaowei
 * @date 2022/01/20
 */
@Component
@Slf4j
public class TopicDemoConsumer {
	/**
	 * 1个消息被多个消费者同时消费, routkey 通配符匹配
	 * 不指定队列名称，系统会自动生成队列名
	 *
	 * @param message 消息
	 * @param channel 通道
	 * @throws Exception 异常
	 */
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(durable = "true"),
			exchange = @Exchange(value = "simpleExchange", type = ExchangeTypes.TOPIC), key = "simple.*"))
	public void onMessage(Message message, Channel channel) throws Exception {
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		try {
			String messageStr = new String(message.getBody(), StandardCharsets.UTF_8);
			log.info("TopicDemoConsumer mq通知，消息体：【{}】", messageStr);

			channel.basicAck(deliveryTag, false);
		} catch (Exception ex) {
			log.error("TopicDemoConsumer error", ex);
			channel.basicAck(deliveryTag, false);
			throw ex;
		}
	}
}
